package com.huluobo.a2307douyindemo.login

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.a2307douyindemo.MainActivity
import com.huluobo.a2307douyindemo.R
import com.huluobo.a2307douyindemo.databinding.ActivityLoginBinding
import com.huluobo.a2307douyindemo.register.RegisterActivity
import com.huluobo.lib_base.bean.Money
import com.huluobo.lib_base.mvvm.BaseActivity
import com.huluobo.lib_base.net.Const
import com.hyphenate.EMCallBack
import com.hyphenate.chat.EMClient
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

@AndroidEntryPoint
class LoginActivity : BaseActivity<ActivityLoginBinding, LoginViewModel>() {
    override fun initData() {
        vm.loginSuccess.observe(this) {
            EMClient.getInstance().login(it.username, it.password, object : EMCallBack {
                override fun onSuccess() {
                    ToastUtils.showLong("欢迎回来:${it.username}")
                    SPUtils.getInstance().put(Const.PARAM_TOKEN, it.token)
                    SPUtils.getInstance().put(Const.PARAM_USERNAME, it.username)
                    //将用户转化为json,方便sp保存
                    val userJson = Gson().toJson(it)
                    SPUtils.getInstance().put(Const.KEY_USER, userJson)
                    val intent = Intent(this@LoginActivity, MainActivity::class.java)
                    val money = Money(username = it.username, money = 10000F)
                    vm.insertMoney(money)
                    startActivity(intent)
                    finish()
                }

                override fun onError(code: Int, error: String?) {
                    Log.e("TagA", "环信登录失败:$code,error:$error")
                }
            })
        }
    }

    override fun initView() {
        binding.loginBtn.setOnClickListener {
            val username = binding.loginUsernameEt.text.toString()
            val password = binding.loginPasswordEt.text.toString()

            if (username.isNotEmpty() && password.isNotEmpty()) {
                val map = mutableMapOf<String, String>()
                map[Const.PARAM_USERNAME] = username
                map[Const.PARAM_PASSWORD] = password

                val json = Gson().toJson(map)
                val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
                vm.login(body)
            } else {
                binding.loginPasswordEt.error = "用户名密码不能为空"
            }
        }

        binding.loginToRegisterTv.setOnClickListener {
            val intent = Intent(this, RegisterActivity::class.java)
            startActivity(intent)
        }
    }
}